package org.beetl.json.action;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.beetl.json.ActionReturn;
import org.beetl.json.DirectOutputValue;
import org.beetl.json.JsonWriter;
import org.beetl.json.OutputNode;
import org.beetl.json.OutputNodeKey;
import org.beetl.json.util.ContextLocal;


/** 格式化输出
 * @author xiandafu
 *
 */
public class FormatAction implements IValueAction {

	String format ;
	public FormatAction(String format){
		this.format = format;
	}
	@Override
	public ActionReturn doit(OutputNodeKey field,Object o,OutputNode thisNode,JsonWriter w) {
		// TODO Auto-generated method stub
		if(o==null) return new ActionReturn(o,ActionReturn.CONTINUE);
		if(o instanceof Double|| o== double.class){
			NumberFormat format = new DecimalFormat();
			return new ActionReturn(new DirectOutputValue(format.format((Double)o)));
			
		}else if(o instanceof BigDecimal){
			NumberFormat format = new DecimalFormat();
			return new ActionReturn(new DirectOutputValue(format.format(((BigDecimal)o).doubleValue())));
		}else if(o instanceof Date){
			SimpleDateFormat df = ContextLocal.get().getDateFormat(format);
			return new ActionReturn(df.format((Date)o));
		}
		
		throw new RuntimeException("not support:"+field.getKey()+" class type="+o.getClass());
	}
	@Override
	public int getIndex() {
		//总是最后一个执行
		return Integer.MAX_VALUE;
	}

}
